package com.huidu.bitrade.job;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.huidu.bitrade.entity.*;
import com.huidu.bitrade.service.*;
import com.huidu.bitrade.constant.TransactionType;
import com.huidu.bitrade.vendor.provider.SMSProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.huidu.bitrade.util.DateUtil;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class MiningsJob {

	@Autowired
    private SMSProvider smsProvider;

	@Autowired
	private MiningOrderDetailService miningOrderDetailService;

	@Autowired
	private MiningOrderService miningOrderService;

	@Autowired
	private MemberWalletService memberWalletService;

	@Autowired
	private MemberTransactionService memberTransactionService;

	@Autowired
	private MemberService memberService;

	//========================
	@Autowired
	private ActivityService activityService;

	/**
	 * 每天晚上10点30发放矿工收益
	 */
	@Scheduled(cron = "0 30 22 * * *")
	public void minings() {
		List<MiningOrder> list = miningOrderService.findAllByMiningStatus(1);
		Date currentDate = DateUtil.getCurrentDate();
		for(MiningOrder item : list) {
			if(currentDate.compareTo(item.getEndTime()) < 0) {
				Member member = memberService.findOne(item.getMemberId());
				// 生成收益
				MemberWallet userWallet = memberWalletService.findByCoinUnitAndMemberId(item.getMiningUnit(), item.getMemberId());
				if(userWallet != null) {
					// 资金记录
					MemberTransaction memberTransaction1 = new MemberTransaction();
					memberTransaction1.setFee(BigDecimal.ZERO);
					memberTransaction1.setAmount(item.getCurrentDaysprofit());
					memberTransaction1.setMemberId(item.getMemberId());
			        memberTransaction1.setSymbol(item.getMiningUnit());
			        memberTransaction1.setType(TransactionType.ACTIVITY_BUY);
			        memberTransaction1.setCreateTime(DateUtil.getCurrentDate());
			        memberTransaction1.setRealFee("0");
			        memberTransaction1.setDiscountFee("0");
			        memberTransaction1 = memberTransactionService.save(memberTransaction1);
			        // 更新余额
			        userWallet.setBalance(userWallet.getBalance().add(item.getCurrentDaysprofit()));
			        memberWalletService.save(userWallet);

			        // 更新矿机数据
			        item.setTotalProfit(item.getTotalProfit().add(item.getCurrentDaysprofit()));
			        item.setMiningedDays(item.getMiningedDays() + 1);
			        miningOrderService.saveAndFlush(item);

			        // 添加矿机产出数据
			        MiningOrderDetail detail = new MiningOrderDetail();
			        detail.setMemberId(item.getMemberId());
			        detail.setCreateTime(DateUtil.getCurrentDate());
			        detail.setMiningOrderId(item.getId());
			        detail.setMiningUnit(item.getMiningUnit());
			        detail.setOutput(item.getCurrentDaysprofit());

			        miningOrderDetailService.saveAndFlush(detail);

			        // 发送短信通知用户
			        try {
						List<String> param = new ArrayList<>();
						param.add("矿机【"+ item.getTitle() + "】");
						param.add("挖矿");
						param.add(item.getCurrentDaysprofit() + " "+item.getMiningUnit() + "，请查收！");
		 				smsProvider.sendMessageByTempId(member.getMobilePhone(), param,7);
		 			} catch (Exception e) {
		 				e.printStackTrace();
		 			}
				}
			}
		}
	}



	/**
	 * 1分钟更新一次
	 */
	@Scheduled(cron = "0 */1 * * * *")
	public void job()throws Exception{
		List<Activity> all = activityService.findAll();
//		显示状态隐藏的和状态介绍的不需要处理
		for (Activity activity:all){
			long currentTime = Calendar.getInstance().getTimeInMillis(); // 当前时间戳
			String strTime = activity.getStartTime();
			String endTime=activity.getEndTime();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date = sdf.parse(strTime);
			Date dateend = sdf.parse(endTime);
			long timestamp = date.getTime();
			long timestampEnd=dateend.getTime();
			if(activity.getStatus().name().equals("IS_TRUE")&&activity.getStep()!=3){//有效状态
//				进度：0：未开始  1：进行中  2：派发中  3：已结束
				/**
				 * 更加开始时间和结束时间判断进行更新状态
				 */
				if (activity.getStep()==0){
					//未开始的活动 时间到则更新状态
					if(currentTime >=timestamp) {
						activity.setStep(1);
						log.info("活动ID"+activity.getId()+"活动状态更新为进行中开放购买");
					}
				}else if (activity.getStep()==2){
					//派发中的活动 时间到则更新状态
					if(currentTime >=timestampEnd) {
						activity.setStep(3);
						log.info("活动ID"+activity.getId()+"活动状态更新为已结束，活动结束");
					}
				}else if(activity.getStep()==1){
					//进行中的活动 进度达到100%时 矿机开始生息
					if (activity.getProgress()>=100){
						activity.setStep(2);
						log.info("活动ID"+activity.getId()+"活动状态更新为派发中，活动开始生息");
					}
				}
			}


		}

	}
}
